package com.zzc.emotisenseclassroom.domain.upload.service.impl;

import cn.hutool.core.io.FileUtil;
import com.zzc.emotisenseclassroom.common.domainexception.NotSupportImgaeEXT;
import com.zzc.emotisenseclassroom.domain.upload.service.FileUploadService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * Copyright Zzc
 * FileName: FileUploadServiceImpl
 * Author:   Zzc
 * Date:     2024/5/514:00
 * Description: 文件上传sevice实现类
 * hISTORY:
 * <author>  <time>     <version>    <desc>
 * 作者姓名   修改时间       版本号       描述
 * Zzc                   1.0.0
 */
@Service
public class FileUploadServiceImpl implements FileUploadService {
    @Override
    public String uploadImage(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();// 名称+后缀
        String mainName = FileUtil.mainName(originalFilename);// 文件名称
        String extName = FileUtil.extName(originalFilename);// 后缀
        if (!("jpg".equalsIgnoreCase(extName) || "png".equalsIgnoreCase(extName))) {
            throw new NotSupportImgaeEXT();
        }

        String fileRealPath =IMAGE_FILE_PATH + PATH_SEPARATOR + originalFilename;
        // 这里的路径是vue项目存放静态资源图片的路径
        File saveFile = new File(fileRealPath);
        if (!saveFile.getParentFile().exists()){
            saveFile.getParentFile().mkdirs();// 父级目录不存在则创建
        }
        if (saveFile.exists()){
            fileRealPath = IMAGE_FILE_PATH + PATH_SEPARATOR + UUID.randomUUID() + "_" + mainName + "." + extName;
            saveFile = new File(fileRealPath);
        }

        file.transferTo(saveFile);
        fileRealPath = fileRealPath.replace(IMAGE_FILE_PATH + PATH_SEPARATOR, "../../../static/img/");

        return fileRealPath;
    }

    @Override
    public String uploadVideo(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String mainName = FileUtil.mainName(originalFilename);
        String extName = FileUtil.extName(originalFilename);


        String fileRealPath =VIDEO_FILE_PATH + PATH_SEPARATOR + originalFilename;
        // 这里的路径是vue项目存放静态资源图片的路径
        File saveFile = new File(fileRealPath);
        if (!saveFile.getParentFile().exists()){
            saveFile.getParentFile().mkdirs();// 父级目录不存在则创建
        }
        if (saveFile.exists()){
            fileRealPath = VIDEO_FILE_PATH + PATH_SEPARATOR + UUID.randomUUID() + "_" + mainName + "." + extName;
            saveFile = new File(fileRealPath);
        }

        file.transferTo(saveFile);
        return fileRealPath;
    }
}
